package com.lmn.filter;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;

/**
 * @describe: 过滤器
 */
public class RequestFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestFilter.class);

    private static final Gson gson = new Gson();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        LOG.info("do filter");
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "18000L");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
        httpResponse.setHeader("Content-Type", "application/json;charset=UTF-8");

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        //注意：如果读取了request中的数据就需要中心wrapper一次
        JsonObject requestData = getRequestInfo(httpRequest);
        ServletRequest requestWrapper = new RequestWrapper(httpRequest, requestData);

        chain.doFilter(requestWrapper, response);
    }


    @Override
    public void destroy() {
        LOG.info("destory");
    }

    /**
     * 获取Http请求的head和body的信息
     */
    public static JsonObject getRequestInfo(HttpServletRequest request) {
        StringBuilder buffer = new StringBuilder();
        try (InputStream inputStream = request.getInputStream()) {
            if (inputStream != null) {
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
                    char[] charBuffer = new char[256];
                    int bytesRead;
                    while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                        buffer.append(charBuffer, 0, bytesRead);
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        JsonObject jsonObject = gson.fromJson(buffer.toString(), JsonObject.class);
        if (jsonObject == null) {
            jsonObject = new JsonObject();
        }

        Enumeration<String> pNames = request.getParameterNames();
        while (pNames.hasMoreElements()) {
            String pName = pNames.nextElement();
            jsonObject.addProperty(pName, request.getParameter(pName));
        }
        return jsonObject;
    }

}
